//
//  PageTitleView.swift
//  liveDemo
//
//  Created by satoshi_uma on 2020/10/20.
//  Copyright © 2020 satoshi_uma. All rights reserved.
//

import UIKit

/// 只能被 类 遵守 ，如果不写 Class 可以被 结构体、枚举类型遵守
protocol PageTitleViewDelegate: class {
    func pageTitleView(titleView: PageTitleView, selectedIndex index: Int)
}

private let ScrollLineH: CGFloat = 2

private let NormalColor: (CGFloat, CGFloat, CGFloat) = (85, 85, 85)
private let SelectColor: (CGFloat, CGFloat, CGFloat) = (255, 128, 0)

class PageTitleView: UIView {
    private var currentIndex: Int = 0
    private var titles: [String]

    weak var delegate: PageTitleViewDelegate?

    //   自定义一个人构造函数
    init(frame: CGRect, titles: [String]) {
        self.titles = titles
        super.init(frame: frame)

        setupUI()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:)没有被执行。")
    }

    /// 懒加载数组
    private lazy var titleLabels: [UILabel] = [UILabel]()

    /// 懒加载 scrollView
    private lazy var scrollView: UIScrollView = {
//        创建scrollView
        let scrollView = UIScrollView()
        scrollView.showsHorizontalScrollIndicator = false // 取消滚动条
        scrollView.scrollsToTop = false // 点击状态栏回到顶部
        scrollView.isPagingEnabled = false // 取消分页
        scrollView.bounces = false // 不能超过内容范围
        return scrollView
    }()

    /// 懒加载 Scroll 的下划线
    private lazy var scrollLine: UIView = {
        let scrollLine = UIView()
        scrollLine.backgroundColor = UIColor(red: SelectColor.0, green: SelectColor.1, blue: SelectColor.2)
        return scrollLine
    }()
}

extension PageTitleView {
    /// 设置UI
    private func setupUI() {
        addSubview(scrollView)
        scrollView.frame = bounds
        setupTitleLabels()
        setupBottomLineAndScrollLine()
    }

    /// 添加 label
    private func setupTitleLabels() {
        let labelW: CGFloat = frame.width / CGFloat(titles.count)
        let labelH: CGFloat = frame.height - ScrollLineH
        let labelY: CGFloat = 0

        for (index, title) in titles.enumerated() {
            let label = UILabel()

            label.text = title
            label.tag = index
            
            if index == 0 {
                label.textColor = UIColor(red: SelectColor.0, green: SelectColor.1, blue: SelectColor.2)
            } else {
                label.textColor = UIColor(red: NormalColor.0, green: NormalColor.1, blue: NormalColor.2)
            }
            
            label.textAlignment = .center
            label.font = UIFont.systemFont(ofSize: 16.0)

            let labelX: CGFloat = labelW * CGFloat(index)
            label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH)

            scrollView.addSubview(label)
            titleLabels.append(label)

            label.isUserInteractionEnabled = true

            let tapGes = UITapGestureRecognizer(target: self, action: #selector(titleLabelClick(tapGes:)))
            label.addGestureRecognizer(tapGes)
        }
    }

    /// 添加 底部横线
    private func setupBottomLineAndScrollLine() {
        let bottomLine = UIView()
        bottomLine.backgroundColor = UIColor.lightGray
        let lineH: CGFloat = 0.5
        bottomLine.frame = CGRect(x: 0, y: frame.height - lineH, width: frame.width, height: lineH)
        addSubview(bottomLine)

        guard let firstLabel = titleLabels.first else { return }
        scrollView.addSubview(scrollLine)
        scrollLine.frame = CGRect(x: firstLabel.frame.origin.x,
                                  y: frame.height - ScrollLineH,
                                  width: firstLabel.frame.width,
                                  height: ScrollLineH)
    }
}

// 监听 label
extension PageTitleView {
    /// label 点击事件
    /// - Parameter tapGes: 手势
    @objc private func titleLabelClick(tapGes: UITapGestureRecognizer) {
       
//        当前 label
        guard let currentLabel = tapGes.view as? UILabel else { return }

        if currentLabel.tag == currentIndex {return}
        
        let oldLabel = titleLabels[currentIndex]

        currentLabel.textColor = UIColor(red: SelectColor.0, green: SelectColor.1, blue: SelectColor.2)
        oldLabel.textColor = UIColor(red: NormalColor.0, green: NormalColor.1, blue: NormalColor.2)

        currentIndex = currentLabel.tag

        let scrollLineX = CGFloat(currentIndex) * scrollLine.frame.width

        UIView.animate(withDuration: 0.15, animations: {
            self.scrollLine.frame.origin.x = scrollLineX
        })

        delegate?.pageTitleView(titleView: self, selectedIndex: currentIndex)
    }
}

// 对外暴露的方法
extension PageTitleView {
    func setTitleWithProgress(progress: CGFloat, sourceIndex: Int, targetIndex: Int) {
        print("PageTitleView____progress\(progress),sourceIndex\(sourceIndex),tagetIndex\(targetIndex)")

        // 取出 Label
        let sourceLabel = titleLabels[sourceIndex]
        let targetLabel = titleLabels[targetIndex]

        // 处理滑块逻辑
        let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x
        let moveX = moveTotalX * progress
        scrollLine.frame.origin.x = sourceLabel.frame.origin.x + moveX

        // 颜色渐变范围
        let colorGradientRange = (SelectColor.0 - NormalColor.0, SelectColor.1 - NormalColor.1, SelectColor.2 - NormalColor.2)

        // 变化的 Label 颜色
        sourceLabel.textColor = UIColor(red: SelectColor.0 - colorGradientRange.0 * progress,
                                        green: SelectColor.1 - colorGradientRange.1 * progress,
                                        blue: SelectColor.2 - colorGradientRange.2 * progress)
        // 变化的 Label 颜色
        targetLabel.textColor = UIColor(red: NormalColor.0 + colorGradientRange.0 * progress,
                                        green: NormalColor.1 + colorGradientRange.1 * progress,
                                        blue: NormalColor.2 + colorGradientRange.2 * progress)

        // 记录最新的 Label
        currentIndex = targetIndex
    }
}
